# -*- coding:utf-8 -*-

import pygame
from pygame.locals import *
import time
import random

# 全局变量，表示爆炸
bomb_flag = 0  # 0:没有爆炸 1：爆炸

class HeroPlane:
    '''玩家飞机'''
    def __init__(self, screen_temp):
        self.x = 200
        self.y = 400
        self.screen = screen_temp  # 游戏窗口
        self.image = pygame.image.load("./images/me.png")
        self.bullet_list = []  # 存储发出的子弹

        # 添加爆炸效果
        self.bomb_image_list = []  # 爆炸图片集
        self.__get_bomb_image()   # 加载爆炸图片
        self.isbomb = False  # 默认爆炸状；True爆炸
        self.image_num = 0  # 显示过的图片数
        self.image_index = 0 # 显示图片的下表变化

    def Bomb(self, isbomb):
        self.isbomb = isbomb

    def display(self):
        # 玩家飞机是否发生爆炸
        if self.isbomb:
            bomb_image = self.bomb_image_list[self.image_index]  # 获取爆炸图片
            self.screen.blit(bomb_image, (self.x, self.y))  # 绘制图片
            self.image_num += 1
            if self.image_num == (self.image_length + 1):
                self.image_num = 0
                self.image_index += 1

                if self.image_index > (self.image_length - 1):
                    self.image_index = 7
                    time.sleep(0.2)
                    # print("玩家飞机发生爆炸，游戏结束……")
                    exit()

        else:
            # 加载玩家飞机到窗口
            self.screen.blit(self.image, (self.x, self.y))
            for bullet in self.bullet_list:
                # 加载子弹到窗口
                bullet.display()
                # 子弹移动
                bullet.move()
                # if bullet.judge():  # 判断子弹是否越界，若是越界，子弹消失
                #     self.bullet_list.remove(bullet)

    def move_left(self):
        self.x -= 10
        if self.x <= 0:
            self.x = 0
    def move_right(self):
        self.x += 10
        if self.x >= 406:
            self.x = 406

    def fire(self):
        # 发射子弹
        self.bullet_list.append(Bullet(self.screen, self.x, self.y))

    def disapper(self, enemy):
        '''监测碰撞效果'''
        # 若是玩家飞机撞墙，发生碰撞效果
        if self.x <= 0 or self.x >= 406:
            # print("玩家飞机撞墙，出现碰撞效果……")
            return True

        # 玩家飞机被敌机子弹达到，发生碰撞效果
        for bo in enemy.bullet_list:
            if bo.x > self.x + 12 and bo.x < self.x + 92 and bo.y > self.x - 100 and bo.y < self.y - 40:
                # print("玩家飞机被击落……")  # 玩家飞机消失，产生碰撞效果
                enemy.bullet_list.remove(bo)  # 敌机子弹消失
                return True

    def __get_bomb_image(self):
        # 加载爆炸图片
        for i in range(1, 8):
            images = pygame.image.load("./images/b" + str(i) +".png")
            self.bomb_image_list.append(images)
        # 图片总数
        self.image_length = len(self.bomb_image_list)


class EnemyPlane:
    '''敌机'''
    def __init__(self, screen):
        self.x = random.choice(range(408))
        self.y = -75
        self.screen = screen
        self.image = pygame.image.load("./images/e" + str(random.randrange(3)) + ".png")
        # self.direction = 'right'  # 默认敌机向右移动
        self.bullet_list = []  # 敌机存放子弹的列表

        # 添加爆炸效果
        self.bomb_image_list = []
        self.__get_bomb_image()
        self.isbomb = False
        self.image_num = 0
        self.image_index = 0

    def Bomb(self, isbomb):
        self.isbomb = isbomb

    def display(self):
        # 爆炸情况
        if self.isbomb:
            bomb_image = self.bomb_image_list[self.image_index]  # 获取爆炸图片
            self.screen.blit(bomb_image, (self.x, self.y))  # 绘制图片
            self.image_num += 1
            if self.image_num == (self.image_length + 1):
                self.image_num = 0
                self.image_index += 1

                if self.image_index > (self.image_length - 1):
                    self.image_index = 7
                    time.sleep(0.2)
                    # print("敌机发生爆炸，游戏结束……")
                    exit()
        else:
            # 绘制敌机，显示到屏幕上
            self.screen.blit(self.image, (self.x, self.y))
            # 加载敌机子弹到屏幕上
            for bullet in self.bullet_list:
                bullet.display()
                bullet.move()
                # if bullet.judge():  #  若是越界，子弹消失
                #     self.bullet_list.remove(bullet)

    def move(self, hero):
        # 敌机移动
        self.y += 2

        # if self.direction == "right":
        #     self.x += 2
        # elif self.direction == "left":
        #     self.x -= 2
        #
        # if self.x > 406:
        #     self.direction = "left"
        # elif self.x < 0:
        #     self.direction = "right"
        # 敌机撞到墙后，监测碰撞效果
        if self.y > 568:
            return True

        # 被玩家子弹打到后，监测碰撞效果
        for bo in hero.bullet_list:
            if bo.x > self.x + 12 and bo.x < self.x + 92 and bo.y > self.x + 20 and bo.y < self.y + 60:
                hero.bullet_list.remove(bo)  # 玩家子弹消失
                return True

    def fire(self):
        # 敌机发射子弹,控制子弹频率
        random_num = random.choice(range(0, 80))
        if random_num == 0 or random_num == 40:
            self.bullet_list.append(EnemyBullet(self.screen, self.x, self.y))

    def __get_bomb_image(self):
        # 加载爆炸图片
        for i in range(1, 8):
            images = pygame.image.load("./images/b" + str(i) + ".png")
            self.bomb_image_list.append(images)
        # 图片总数
        self.image_length = len(self.bomb_image_list)


class Bullet:
    '''玩家子弹'''
    def __init__(self, screen, x, y):
        self.x = x + 53
        self.y = y
        self.screen = screen
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        # 加载子弹到屏幕上
        self.screen.blit(self.image, (self.x, self.y))

    def move(self):
        # 子弹移动变化
        self.y -= 10

    def judge(self):
        # 子弹是否越界
        if self.y < 0:
            return True
        else:
            return False


class EnemyBullet:
    '''敌机子弹'''
    def __init__(self, screen, x, y):
        self.x = x + 53
        self.y = y + 87
        self.screen = screen
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        # 绘制敌机子弹
        self.screen.blit(self.image, (self.x, self.y))

    def move(self):
        self.y += 8

    # def judge(self):
    #     敌机是否越界
    #     if self.y > 568:
    #         return True
    #     else:
    #         return False

def key_control(hero_temp):
    '''键盘控制 事件'''
    for event in pygame.event.get():
        # 判断是否点击了退出按钮
        if event.type == QUIT:
            print("exit()")
            exit()
        # 判断是否是按下了键
        elif event.type == KEYDOWN:
            # 监测按键是是否是a或left
            if event.key == K_a or event.key ==K_LEFT:
                print("Left....")
                hero_temp.move_left()

            # 监测按键是否是D或right
            elif event.key == K_d or event.key == K_RIGHT:
                print("Right....")
                hero_temp.move_right()

            # 监测按键是否是空格键
            elif event.key == K_SPACE:
                print("Space....")
                hero_temp.fire()


def main():
    '''主程序函数'''
    # 创建窗口
    screen = pygame.display.set_mode((512, 568), 0, 0)

    # 创建背景图片
    background = pygame.image.load("./images/bg2.jpg")

    # 创建玩家飞机
    hero = HeroPlane(screen)

    # 存放敌机列表
    enemyList = []

    m = -968
    while True:
        # 显示屏幕
        screen.blit(background, (0, m))
        m += 2
        if m > -200:
            m = -968

        # 显示玩家飞机
        hero.display()

        # 随机绘制敌机
        if random.choice(range(50)) == 10:
            enemyList.append(EnemyPlane(screen))

        for en in enemyList:
            en.display() # 显示敌机
            en.move(hero) # 敌机移动
            en.fire()  # 敌机发射子弹
            if en.move(hero):   # 敌机移动,是否右碰撞
                en.isbomb = True
                # enemyList.remove(en)  # 有碰撞，敌机消失
                # print("敌机被射中，发生爆炸……")

            if hero.disapper(en):   # 敌机发射的子弹，是否会与玩家飞机发生碰撞
                hero.isbomb = True
                # print("玩家飞机被监测到碰撞事件，玩家飞机已无生命……")

        # 调用按键功能
        key_control(hero)

        # 显示更新
        pygame.display.update()

        # 停留时间
        time.sleep(0.04)



if __name__ == "__main__":
    main()